<template>
  <!--  客户投诉管理（区域经理）  -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="commonTopFilter"
      :list="topFilterInit"
      :cols="3"
      labelWidth="90"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
      @resetChange="resetHandle"
    ></TopFilter>
    <!-- 按钮 -->

    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :rowstyles="rowStyleData"
      :onRowSelectChange="selectChange"
      columnsRef="notification_maintain_index_01"
      :onColumnsChange="columns => this.columns = columns"
      :onSyncTableData="syncComplainData"
    >
      <template slot="controls">
        <multiuse-button type="primary" :click="exportFileBtn.bind(this)">导出</multiuse-button>
      </template>
    </FilterTable>

    <BaseDialog :visible.sync="selectDelearFlag" title="服务中心选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple" />
    </BaseDialog>

    <!-- 响应窗口 -->
    <Drawer
      :visible.sync="visibleDrawer"
      :title="title"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ccResponse v-model="initData" :ccId="ccId" :ccResponseData="ccResponseData" @close="infoClose" />
    </Drawer>

    <!-- 审核窗口 -->
    <Drawer
      :visible.sync="visibleDrawer2"
      :title="title"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ccExamine v-model="initData" :ccId="ccId" :ccResponseData="ccResponseData" @close="infoClose" />
    </Drawer>

    <!-- 明细窗口 -->
    <Drawer
      :visible.sync="visibleDrawer3"
      :title="title"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <detail v-model="initData" :ccId="ccId" :ccResponseData="ccResponseData" @close="infoClose" />
    </Drawer>
  </div>
</template>

<script>
import ccResponse from './ccResponse';
import ccExamine from './ccExamine';
import detail from './detail';
import { exportExcelFile } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import { region } from '@/api/cms-common/region';//行政区域
import { getComplainList,getCusForExport,getListForExport} from '@/api/customerRepair/customerComplaint/customerComplaintQuery';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
export default {
  mixins: [dictionary,region],
  components: {
    //infoModal
    DealerList,
    ccExamine,
    ccResponse,
    detail
  },
  props:{
    defaultStatus: {
      type: [String,Array],
      required: false,
      default:()=>{
        return '';
      }
    }
  },
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchApi: getComplainList, //api 接口 table请求数据入口
      fetchParams: {isRegionalManager:true},
      visibleDrawer: false,
      visibleDrawer2: false,
      visibleDrawer3: false,
      initData: {},
      title: '',
      ccId:'',
      itemList:{},
      saveLoading: false,
      selectDealerData: [],
      selectDelearFlag: false,
      dealerData: [],
      exportLoading: false, // 导出加载中
      rowSelectData: [],
      ccResponseData:'',
      rowStyleData:[]
    };
  },
  mounted() {
    this.initProvince();
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    syncComplainData(data,isFirst){
      console.log('data',data)
      if (!data.length) return;
      data.forEach(x => {
        if (x.isRed) {
          this.rowStyleData.push({ row: x, styles: { background: '#ffcccc' } });
        }else{
          this.rowStyleData.push({ row: x, styles: { background: '#fff' } });
        }
      });
    },
    topFilterInitFun() {
      let bt = { required: true, message: '必填', trigger: ['change', 'blur'] };
      let btl = [bt,];
      return [
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '投诉人手机', fieldName: 'cusMobile', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '投诉人姓名', fieldName: 'cusName', placeholder: '请选择', initialValue: '' },
        { type: 'SELECT', label: '投诉类型', fieldName: 'ccType', placeholder: '请选择', initialValue: '', itemList: this.createDictList('5586') },
        { type: 'SELECT', label: '投诉等级', fieldName: 'ccLevel', placeholder: '请选择', initialValue: '', itemList: this.createDictList('5587') },
        { type: 'SELECT', label: '单据状态', fieldName: 'ccState', placeholder: '请选择', initialValue: '', itemList: this.createDictList('5589',[55891007]) },
        { type: 'RANGE_DATE', label: '投诉日期', fieldName: 'complaintDateFrom|complaintDateTo', placeholder: '请选择', initialValue: '' },
        {
          type: 'INPUT',
          label: '经销服务商',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
        },
        { type: 'INPUT', label: '投诉单号', fieldName: 'ccCode', placeholder: '请选择', initialValue: '' },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [],change: props => this.initCity(props)},
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initTown(props)}
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          sorter: true,
          fixed: 'left',
          render: props => {
            let disabled = props.row.ccState == '55891005' || props.row.ccState == '55891007' || props.row.ccState == '55891008' || props.row.ccState == '55891004' ? true : false;
            let examine = props.row.ccState == '55891004' ? false : true;
            return (
              <div>
                <el-button size="mini" type="text" disabled={disabled} onClick={() => this.ccResponse(props.row, 'edit')}>
                  响应
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={examine} onClick={() => this.ccExamine(props.row, 'edit')}>
                  审核
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={false} onClick={() => this.detail(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        { title: '投诉单号', dataIndex: 'ccCode', sorter: true},
        { title: '投诉日期', dataIndex: 'ccDate',dateFormat: 'yyyy-MM-dd HH:mm', sorter: true },
        {
          title: '单据状态',
          dataIndex: 'ccState',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.ccState, '5589')}</span>;
          }
        },
        { title: '是否响应', dataIndex: 'isResponse', sorter: true},
        { title: '车主姓名', dataIndex: 'owenrName', sorter: true },
        { title: '车主手机', dataIndex: 'owenrMobile', sorter: true },
        { title: '投诉人姓名', dataIndex: 'cusName', sorter: true },
        { title: '投诉人手机', dataIndex: 'cusMobile', sorter: true },
        { title: '联系电话', dataIndex: 'cusTel', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true, width: 150 },
        { title: '车系', dataIndex: 'series', sorter: true },
        { title: '车型', dataIndex: 'model', sorter: true },
        { title: '车牌号', dataIndex: 'license', sorter: true },
        { title: '购车时间', dataIndex: 'purchaseTime', sorter: true,dateFormat: 'yyyy-MM-dd HH:mm:ss' },
        { title: '行驶里程', dataIndex: 'mileage', sorter: true },
        { title: '投诉渠道', dataIndex: 'ccChannel', sorter: true ,
         render: props => {
            return <span>{this.createDictText(props.row.ccChannel, '5518')}</span>;
          }},
        { title: '投诉等级', dataIndex: 'ccLevel', sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.ccLevel, '5587')}</span>;
          }},
        { title: '投诉类型', dataIndex: 'ccType', sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.ccType, '5586')}</span>;
          }},
        { title: '省份', dataIndex: 'provinceName', sorter: true },
        { title: '城市', dataIndex: 'cityName', sorter: true },
        { title: '经销服务商代码', dataIndex: 'dealerCode', sorter: true },
        { title: '经销服务商简称', dataIndex: 'dealerShortName', sorter: true },
        { title: '响应时间', dataIndex: 'reAt', sorter: true ,dateFormat: 'yyyy-MM-dd HH:mm:ss'},
        { title: '处理日期', dataIndex: 'opAt', sorter: true ,dateFormat: 'yyyy-MM-dd HH:mm:ss'},
        { title: '结案日期', dataIndex: 'closeDate', sorter: true,dateFormat: 'yyyy-MM-dd HH:mm:ss' }
      ];
    },
    //初始化所在省份
    async initProvince(){
      let pl = await this.createRegionList();
      this.topFilterInit.find(item => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId){
      if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterInit.find(item => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
      //清除区县
      let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
      district.itemList = [];
      district.initialValue = '';
    },
    //初始化所在县市数据
    async initTown(cityId){
      if(!cityId || cityId==null || typeof(cityId)=='undefined'){
        return;
      }
      let td = this.cityData[cityId].children;
      let tl = this.createSubRegionList(td);
      //初始化区县，清除原值
      let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
      district.itemList = tl;
      district.initialValue = '';
    },
    //搜索获取数据
    changeHandle(val) {
      console.log('selectDealerData',this.selectDealerData);
      this.fetchParams = Object.assign({},val,{ dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null,isRegionalManager:true });
    },
    //展开收起时触发
    collapseHandle() {},
    ccResponse(row, type) {
      this.title = '响应';
      this.initData = {
        type: type, // add-edit-show
        id: 1001
      }; //行id
      this.ccId = row['ccId'];
      this.ccResponseData = row;
      this.visibleDrawer = true;
    },
    //导出
    async exportFileBtn() {
      let params = { ...this.fetchParams};
      console.log(params, '导出::');
      let res = await getCusForExport(params);
      console.log(res.data, '导出::');
      try {
        exportExcelFile(res.data, '客户投诉管理');
      } catch (e) {
        console.log(e, '错误::');
      }
    },
    ccExamine(row, type) {
      this.title = '审核';
      this.initData = {
        type: type, // add-edit-show
        id: 1001
      }; //行id
      this.ccId = row['ccId'];
      this.ccResponseData = row;
      this.visibleDrawer2 = true;
    },

    detail(row, type) {
      this.title = '明细';
      this.initData = {
        type: type, // add-edit-show
        id: 1001
      }; //行id
      this.ccId = row['ccId'];
      this.ccResponseData = row;
      this.visibleDrawer3 = true;
    },

    Delearclose() {
      this.selectDelearFlag = false;
    },

    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    //关闭详情 rData 是页面关闭回调回来的数据
    infoClose(rData) {
      this.visibleDrawer = false;
      this.visibleDrawer2 = false;
      this.visibleDrawer3 = false;
      if (rData.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },

    validReturnDate(res) {
      if (res.resultCode === 200) {
        this.saveLoading = false;
        this.$notify.success({ title: '提示信息', message: '操作成功!' });
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      } else {
        this.saveLoading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '操作失败!' });
      }
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },
    selectChange(val) {
      console.log('val', val);
      this.rowSelectData = val;
    },
  }
};
</script>

<style lang="less" scoped>
</style>
